package cn.tataben.sharding.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.tataben.sharding.base.DataResponse;
import cn.tataben.sharding.base.Generator;
import cn.tataben.sharding.base.PageResponse;
import cn.tataben.sharding.base.Response;
import cn.tataben.sharding.domains.pos.UserPo;
import cn.tataben.sharding.domains.vos.UserVo;
import cn.tataben.sharding.mappers.UserMapper;

@Service
@Transactional(readOnly = true)
public class UserService {

	@Autowired private UserMapper userMapper;

	@Transactional(readOnly = false)
	public Response add() throws Exception {

		for(int i = 100; i < 150; i++) {
			UserPo record = new UserPo(i, "username" + i, "password" + i);
			userMapper.insert(record);
        }

		return new Response();
	}

	@Transactional(readOnly = false)
	public Response delete(int id) throws Exception {
		userMapper.delete(id);
		return new Response();
	}

	@Transactional(readOnly = false)
	public Response update(UserVo user) throws Exception {
		UserPo record = Generator.convert(user, UserPo.class);
		userMapper.update(record);
		return new Response();
	}

	public DataResponse<UserVo> select(int id) throws Exception {
		return new DataResponse<>(Generator.convert(userMapper.select(id), UserVo.class));
	}

	public PageResponse<List<UserVo>> selects(String query, String order, int page, int rows) throws Exception {
		PageResponse<List<UserVo>> resp = new PageResponse<List<UserVo>>();
		List<UserPo> users = userMapper.selects(page, rows, order, query);
		resp.setData(Generator.convert(users, UserVo.class));
		resp.setTotal(userMapper.count(query));
		return resp;
	}

}